package com.example.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.example.reggie.bean.AddressBook;
import com.example.reggie.service.AddressBookService;
import com.example.reggie.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/addressBook")
public class AddressBookController {
    @Autowired
    private AddressBookService addressBookService;

    @GetMapping("/list")
    public R<List> allList(){
       List<AddressBook> list= addressBookService.list();
       return R.success(list);
    }
    @Transactional
    @PutMapping("/default")
    public R<String> setDefault(@RequestBody AddressBook addressBook){
        Long id = addressBook.getId();
        LambdaUpdateWrapper<AddressBook> updateWrapper=new LambdaUpdateWrapper<>();
        updateWrapper.set(AddressBook::getIsDefault,0);
        addressBookService.update(updateWrapper);

        AddressBook addressBookObj=addressBookService.getById(id);
        addressBookObj.setIsDefault(1);
        addressBookService.updateById(addressBookObj);

        return R.success("设置成功");
    }

    @GetMapping("/{id}")
    public R<AddressBook> getOne(@PathVariable("id") Long id){
        AddressBook addressBook=addressBookService.getById(id);
        return R.success(addressBook);
    }

    @PutMapping
    public R<String> updateOne(@RequestBody AddressBook addressBook){
        addressBookService.updateById(addressBook);
        return R.success("编辑成功");
    }

    @DeleteMapping
    public R<String> delete(@RequestParam List<Long> ids){
        addressBookService.removeByIds(ids);
        return R.success("删除成功");
    }

    @PostMapping
    public R<String> add(@RequestBody AddressBook addressBook){
        addressBookService.save(addressBook);
        return R.success("新增成功");
    }

    @GetMapping("/default")
    public R<AddressBook> defaultAddressBook(){
        LambdaQueryWrapper<AddressBook> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(AddressBook::getIsDefault,true);
        AddressBook addressBook=addressBookService.getOne(queryWrapper);
        return R.success(addressBook);
    }
}
